package com.hj.excellibrary.impl;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.hj.excellibrary.NotFindSheetException;
import com.hj.excellibrary.annotation.CellStyle;
import com.hj.excellibrary.annotation.ExcelWriteAdapter;
import com.hj.excellibrary.annotation.ExcelWriteCell;
import com.hj.excellibrary.service.IConvertParserAdapter;
import com.hj.excellibrary.service.IExcelUtils;
import com.hj.excellibrary.service.IParseListener;
import com.hj.excellibrary.service.IParser;
import com.hj.excellibrary.service.ITabContext;
import com.hj.excellibrary.service.IWriteListener;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.FontUnderline;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetProtection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

public class ExcelImpl2 implements IExcelUtils {

    private static final String TAG = "ExcelImpl";

    private final Handler handler = new Handler(Looper.getMainLooper());

    @Override
    public <T> void readExcelXSSF(InputStream inputStream, Class<T> aClass, IParseListener<T> listener) {
        IParser<T> parser = new ParserImpl<>();
        new Thread(() -> {
            try {
                XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
                doReadExcelXLSX(parser, workbook, aClass, listener);
            } catch (IOException | NotFindSheetException e) {
                e.printStackTrace();
                handler.post(() -> listener.onParseError(e));
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public <T> void readExcelHSSF(InputStream inputStream, Class<T> tClass, IParseListener<T> listener) {
        IParser<T> parser = new ParserImpl<>();
        new Thread(() -> {
            try {
                HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
                doReadExcelXLSX(parser, workbook, tClass, listener);
            } catch (IOException | NotFindSheetException e) {
                e.printStackTrace();
                handler.post(() -> listener.onParseError(e));
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public <T> void writeExcelXSSF(OutputStream outputStream, List<T> data, IWriteListener listener) {
        if (data == null || data.size() <= 0) {
            return;
        }
        // 创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet1 = workbook.createSheet("Full");
        XSSFSheet sheet2 = workbook.createSheet("Match");
        try {
            sheet1 = writeTableHead(workbook, data.get(0), sheet1);
            writeExcelData(data, sheet1, workbook, listener);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                List<T> filteredData = data.stream()
                        .filter(item -> {
                            try {
                                // 使用反射获取 status 字段的值
                                Field statusField = item.getClass().getDeclaredField("status");
                                statusField.setAccessible(true);
                                int statusValue = (int) statusField.get(item);
                                return statusValue == 1;
                            } catch (NoSuchFieldException | IllegalAccessException e) {
                                e.printStackTrace();
                                return false;
                            }
                        })
                        .collect(Collectors.toList());

                sheet2 = writeTableHead(workbook, filteredData.get(0), sheet2);
                writeExcelData(filteredData, sheet2, workbook, listener);
            }
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
            handler.post(() -> listener.onWriteError(e));
            return;
        }

        // 设置每列的宽度
        setColumnWidths(sheet1, data, listener);
        setColumnWidths(sheet2, data, listener);


        // 设置筛选模式
        setAutoFilter(sheet1, data);
        setAutoFilter(sheet2, data);

        // 保护工作表
        protectSheet(sheet1);
        protectSheet(sheet2);

        // 写入输出流
        try {
            workbook.write(outputStream);
            outputStream.flush();
            if (listener != null) {
                handler.post(listener::onEndWrite);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (listener != null) {
                handler.post(() -> listener.onWriteError(e));
            }
        } finally {
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private <T> void writeExcelData(List<T> data, XSSFSheet sheet, XSSFWorkbook workbook, IWriteListener listener) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            boolean isStatus = false;

            //写入数据
            for (int i = 0; i < data.size(); i++) {
                XSSFRow row = sheet.createRow(i + 1);
                T t = data.get(i);
                try {
                    Field statusField  = t.getClass().getDeclaredField("status");
                    Field epcField  = t.getClass().getDeclaredField("epc");
                    statusField.setAccessible(true);
                    epcField.setAccessible(true);
                    int statusValue = (int) statusField.get(t);
                    isStatus = statusValue == 1 ? true : false;
                }catch (Exception e){
                    Log.e(TAG, e.toString());
                }

                for (Field declaredField : t.getClass().getDeclaredFields()) {
                    ExcelWriteCell excelWriteCell = declaredField.getAnnotation(ExcelWriteCell.class);
                    CellStyle cellStyle = declaredField.getAnnotation(CellStyle.class);
                    ExcelWriteAdapter excelWriteAdapter = declaredField.getAnnotation(ExcelWriteAdapter.class);
                    if (excelWriteCell != null) {
                        XSSFCell cell = row.createCell(excelWriteCell.writeIndex());
                        try {
                            cell.setCellValue(String.valueOf(declaredField.get(t)));
                            setCellStyle(workbook, cell, cellStyle, sheet, isStatus);
                        } catch (IllegalAccessException e) {
                            handler.post(() -> listener.onWriteError(e));
                        }
                    }
                    if (excelWriteAdapter != null) {
                        try {
                            IConvertParserAdapter adapter = (IConvertParserAdapter) excelWriteAdapter.adapter().newInstance();
                            adapter.convert((column, value, columnIndex) -> {
                                XSSFCell cell = row.createCell(columnIndex);
                                cell.setCellValue(String.valueOf(value));
                            }, declaredField.get(t));
                        } catch (IllegalAccessException | InstantiationException e) {
                            handler.post(() -> listener.onWriteError(e));
                        }
                    }
                }
            }

        }
    }

    private <T> void setColumnWidths(XSSFSheet sheet, List<T> data, IWriteListener listener) {
        for (int colIndex = 0; colIndex < data.get(0).getClass().getDeclaredFields().length; colIndex++) {
            int maxWidth = 0;
            for (T t : data) {
                Field[] fields = t.getClass().getDeclaredFields();
                if (colIndex < fields.length) {
                    Field field = fields[colIndex];
                    ExcelWriteCell excelWriteCell = field.getAnnotation(ExcelWriteCell.class);
                    if (excelWriteCell != null) {
                        try {
                            field.setAccessible(true);
                            String value = String.valueOf(field.get(t));
                            maxWidth = Math.max(maxWidth, value.length());
                        } catch (IllegalAccessException e) {
                            handler.post(() -> listener.onWriteError(e));
                        }
                    }
                }
            }
            if (colIndex == 0 || colIndex == 5) {
                sheet.setColumnWidth(colIndex, 2999);
            } else {
                sheet.setColumnWidth(colIndex, 8888);
            }
        }
    }

    private <T> void setAutoFilter(XSSFSheet sheet, List<T> data) {
        int lastRowNum = data.size(); // 数据行数
        int lastColumnNum = data.get(0).getClass().getDeclaredFields().length; // 列数
        sheet.setAutoFilter(new CellRangeAddress(0, lastRowNum, 0, lastColumnNum - 1));
    }

    private void protectSheet(XSSFSheet sheet) {
        sheet.protectSheet("SPITxBOC");
        CTSheetProtection sheetProtection = sheet.getCTWorksheet().getSheetProtection();
        sheetProtection.setFormatRows(false);
        sheetProtection.setFormatColumns(false);
        sheetProtection.setSort(false);
        sheetProtection.setAutoFilter(false);
    }

    private void setCellStyle(XSSFWorkbook workbook, XSSFCell cell, CellStyle cellStyle, XSSFSheet sheet, boolean isStatus) {
        if (cellStyle == null) {
            return;
        }
        boolean bold = cellStyle.bold();
        boolean italic = cellStyle.italic();
        FontUnderline underline = cellStyle.underline();
        HorizontalAlignment horizontalAlignment = cellStyle.horizontalAlign();
        VerticalAlignment verticalAlignment = cellStyle.verticalAlign();
        XSSFCellStyle cellStyle1 = workbook.createCellStyle();

        String sheetName = sheet.getSheetName();
        if (sheetName.equals("Full") && isStatus) {
            cellStyle1.setFillForegroundColor(IndexedColors.YELLOW.index);
            cellStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 设置填充模式为实心
        }

        cellStyle1.setVerticalAlignment(verticalAlignment);
        cellStyle1.setAlignment(horizontalAlignment);
        XSSFFont font = workbook.createFont();
        font.setBold(bold);
        font.setItalic(italic);
//        font.setUnderline(underline);
        cellStyle1.setFont(font);
        cell.setCellStyle(cellStyle1);
    }

    private <T> XSSFSheet writeTableHead(XSSFWorkbook workbook, T t, XSSFSheet sheet) throws IllegalAccessException, InstantiationException {
        XSSFRow row = sheet.createRow(0);
        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            ExcelWriteCell annotation = declaredField.getAnnotation(ExcelWriteCell.class);
            CellStyle cellStyle = declaredField.getAnnotation(CellStyle.class);
            if (annotation != null) {
                Log.d(TAG, "writeTableHead: writeName = " + annotation.writeName());
                Log.d(TAG, "writeTableHead: writeIndex = " + annotation.writeIndex());
                XSSFCell cell = row.createCell(annotation.writeIndex());
                cell.setCellValue(annotation.writeName());
                setCellStyle(workbook, cell, cellStyle, sheet, false);
            }
        }
        for (Field declaredField : declaredFields) {
            ExcelWriteAdapter excelWriteAdapter = declaredField.getAnnotation(ExcelWriteAdapter.class);
            CellStyle cellStyle = declaredField.getAnnotation(CellStyle.class);
            if (excelWriteAdapter != null) {
                IConvertParserAdapter adapter = (IConvertParserAdapter) excelWriteAdapter.adapter().newInstance();
                adapter.convert((column, value, columnIndex) -> {
                    Log.d(TAG, "writeTableHead: writeName = " + column);
                    Log.d(TAG, "writeTableHead: writeIndex = " + columnIndex);
                    XSSFCell cell = row.createCell(columnIndex);
                    cell.setCellValue(String.valueOf(column));
                    setCellStyle(workbook, cell, cellStyle,  sheet, false);
                }, declaredField.get(t));
            }
        }
        return sheet;
    }

    private <T> void doReadExcelXLSX(IParser<T> parser, Workbook workbook, Class<T> aClass, IParseListener<T> listener) throws NotFindSheetException {
        ITabContext tabContexts = parser.parseXSSFContext(workbook, aClass);
        Log.d(TAG, "doReadExcelXLSX: tabContexts = " + tabContexts.toString());
        parser.doParse(workbook, tabContexts, aClass, listener);
    }
}
